package com.rongzhe.house.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.rongzhe.house.R;
import com.rongzhe.house.presenter.H5Presenter;

import org.w3c.dom.Text;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 提供H5显示的页面
 * Created by yadong on 2017/5/16.
 */
public class H5BaseActivity extends BaseActivity<H5Presenter> {
    public static final String EXTRA_URL = "web_url";
    private static final String EXTRA_BACK_TO_FINISH = "back_to_finish";
    private static final String EXTRA_TITLE = "title";

    @BindView(R.id.webview)
    BridgeWebView mWebView;
    @BindView(R.id.progress)
    ProgressBar mProgreess;
    private H5Presenter mPresenter;
    private boolean mBackToFinish = false;

    public static final Intent getH5BaseActivityIntent(Context context, String actionTitle,
                                                       String url) {
        Intent intent = new Intent(context, H5BaseActivity.class);
        intent.putExtra(EXTRA_URL, url);
        intent.putExtra(EXTRA_TITLE, actionTitle);
        return intent;
    }

    public static final Intent markAsPageBack(Intent intent) {
        return intent.putExtra(EXTRA_BACK_TO_FINISH, true);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutRes());
        mPresenter = new H5Presenter(this);
        ButterKnife.bind(this);
        if (getIntent() != null) {
            mBackToFinish = getIntent().getBooleanExtra(EXTRA_BACK_TO_FINISH, false);
        }
        if (mProgreess == null || mWebView == null) {
            throw new IllegalStateException("继承本类" + getClass().getSimpleName()
                    + " 必须在layout资源文件中包含activity_h5_base.xml");
        }
        configActionBar();
        initWebView();
    }

    public String getUrl() {
        if (getIntent() != null) {
            return getIntent().getStringExtra(EXTRA_URL);
        }
        return null;
    }

    protected void configWebView(WebView webView) {
    }

    protected int getLayoutRes() {
        return R.layout.activity_h5_base;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWebView.onResume();
        //对网页显示设置字体缩放, 禁止字体大小改变, 防止页面布局错乱
        Resources resource = getResources();
        Configuration configuration = resource.getConfiguration();
        configuration.fontScale = 1.0f;//设置字体的缩放比例
        resource.updateConfiguration(configuration, resource.getDisplayMetrics());
    }

    @Override
    protected boolean showActionBar() {
        return (getIntent() != null && !TextUtils.isEmpty(getIntent().getStringExtra(EXTRA_TITLE)));
    }

    @Override
    protected String getActionTitle() {
        return getIntent() == null ? null : getIntent().getStringExtra(EXTRA_TITLE);
    }

    @Override
    public void onPause() {
        super.onPause();
        mWebView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected H5Presenter createPresenter() {
        return new H5Presenter(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack() && !mBackToFinish) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    public void loadUrl(String url) {
        mWebView.loadUrl(url);
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) { // 进度
            super.onProgressChanged(view, newProgress);

            if (newProgress == 100) {
                mProgreess.setVisibility(View.GONE);// 加载完网页进度条消失
            } else {
                mProgreess.setVisibility(View.VISIBLE);// 开始加载网页时显示进度条
                mProgreess.setProgress(newProgress);// 设置进度值
            }
        }
    }

    public BridgeWebView getWebView() {
        return mWebView;
    }

    //初始化webview
    private void initWebView() {
        mWebView = (BridgeWebView) findViewById(R.id.webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true); // 启用支持javascript
        webSettings.setAllowFileAccess(true);// 可以访问文件

        webSettings.setBuiltInZoomControls(true);// 支持缩放
        if (Build.VERSION.SDK_INT >= 11) {
            webSettings.setPluginState(WebSettings.PluginState.ON);
            webSettings.setDisplayZoomControls(false);// 支持缩放
        }
        webSettings.setSupportZoom(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 扩大比例的缩放
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        // 自适应屏幕
        if (Build.VERSION.SDK_INT > 14) {
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        }
        webSettings.setBlockNetworkImage(false);// 不能屏蔽图片，验证码是图片
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        // 设置web chrome client用于更新progress
        mWebView.setWebChromeClient(new MyWebChromeClient());
        configWebView(mWebView);
        mPresenter.configWebView(mWebView);
    }
}
